import { Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { SearchRequestDto, SearchResultDto } from '../dto/search.dto';
import { FormatUtil } from '../utils/format.util';

@Injectable()
export class SearchService {
  constructor(private readonly prismaService: PrismaService) {}

  async getRecords(data: SearchRequestDto): Promise<SearchResultDto> {
    const getRecordsCondition = {};
    if (data.query) {
      Object.assign(getRecordsCondition, {
        OR: [
          {
            title: {
              contains: data.query,
            },
          },
          {
            hash: data.query,
          },
        ],
      });
    }
    const shares = await this.prismaService.peerShares.findMany({
      skip: data.skip ?? 0,
      take: data.take ?? 10,
      where: getRecordsCondition,
    });

    return {
      data: shares.map((share) => ({
        hash: share.hash,
        title: share.title,
        size: FormatUtil.formatBytes(share.size),
        category: share.category,
        create_time: share.createtime,
        added_time: share.added_time,
      })),
      total: await this.getTotal(),
    };
  }

  async getTotal(): Promise<number> {
    return await this.prismaService.peerShares.count();
  }

  async deleteRecord(hash: string) {
    try {
      await this.prismaService.peerShares.delete({
        where: {
          hash,
        },
      });

      await this.prismaService.deleted_records.create({
        data: {
          hash,
          deleted_time: new Date().getTime() / 1000,
        },
      });
    } catch (error) {}
  }
}
